#include <STC15F2K60S2.H>
#include <stdio.h>
#include <string.h>

#define Y0 P2=0x1f & (P2 | 0xe0)
#define Y4 P2=0x9f & (P2 | 0xe0)
#define Y5 P2=0xbf & (P2 | 0xe0)

bit busy = 0;
bit uart_flag = 0,uart_work_flag = 0;
unsigned int uart_num = 0;
void UartInit(void)		//9600bps@12.000MHz
{
	SCON = 0x50;		//8位数据,可变波特率
	AUXR &= 0xBF;		//定时器1时钟为Fosc/12,即12T
	AUXR &= 0xFE;		//串口1选择定时器1为波特率发生器
	TMOD &= 0x0F;		//设定定时器1为16位自动重装方式
	TL1 = 0xE6;		//设定定时初值
	TH1 = 0xFF;		//设定定时初值
	ET1 = 0;		//禁止定时器1中断
	TR1 = 1;		//启动定时器1
    
    ES = 1;
    EA = 1;
}

void Timer2Init(void)		//2毫秒@12.000MHz
{
	AUXR |= 0x04;		//定时器时钟1T模式
	T2L = 0x40;		//设置定时初值
	T2H = 0xA2;		//设置定时初值
	AUXR |= 0x10;		//定时器2开始计时
    
    IE2 = 0xff & (IE2 | 0x04);
//    EA = 1;
}

char rx_dat[20] = {0};

void uart_work(void);
void SendData(char dat);
void SendString(char *s);

void main()
{
	P04=0;P06=0;Y5;Y0;
	P0=0xff;Y4;Y0;
    Timer2Init();
    UartInit();
	while(1)
	{
        if(uart_work_flag == 1)
        {
            uart_work_flag = 0;
            uart_work();
        }
	}
}

void Uart() interrupt 4
{
    if (RI)
    {
        RI = 0;                 //清除RI位
        uart_flag = 1;
        rx_dat[uart_num++] = SBUF;
        if(uart_num >= 20)
        {
            uart_num = 0;
        }
    }
    if (TI)
    {
        TI = 0;                 //清除TI位
        busy = 0;               //清忙标志
    }
}
unsigned char uart_timer = 0;
void timer2_int (void) interrupt 12
{
    if(uart_flag == 1)
    {
        uart_timer ++;
        if(uart_timer >= 25)
        {
            uart_timer = 0;
            uart_work_flag = 1;
        }
    }
}
char send_dat[20] = {0};
void uart_work(void)
{
    if(uart_flag == 1)
    {
        uart_flag = 0;
        if(strcmp(rx_dat,"on") == 0)
        {
            SendString("on ok");
        }
        else if(strcmp(rx_dat,"off") == 0)
        {
            SendString("off ok");
        }
        else 
        {
            SendString("error");
        }
        memset(rx_dat,0,sizeof(rx_dat));
        uart_num = 0;
        
    }
}

void SendData(char dat)
{
    while (busy);               //等待前面的数据发送完成
    busy = 1;
    SBUF = dat;                 //写数据到UART数据寄存器
}

/*----------------------------
发送字符串
----------------------------*/
void SendString(char *s)
{
    while (*s)                  //检测字符串结束标志
    {
        SendData(*s++);         //发送当前字符
    }
}



